<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/12/8
 * Time: 15:05
 */

namespace app\zyhsapi\model;

use think\Log;
use traits\model\SoftDelete;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUserQuestionComment extends BaseCacheZyhs
{
    use SoftDelete;

    protected $table = 'good_wechat.zyhs_user_question_comment';
    protected $cacheModel = 'question_answer.question_comment';

    protected $deleteTime = 'delete_time';

    public function saveData($data)
    {
        try
        {
            $id = $this->insertGetId($data);
        }
        catch (\Exception $e)
        {
            $id = 0;
        }
        return $id;
    }

    public function updateData($taskId, $astrId, $data)
    {
        try
        {
            $this->where('task_id', $taskId)->update($data);
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $taskId)->rmCache();
            (new ZyhsAstrTasks())->UpdateData($taskId, $astrId, ['is_comment' => 2]);
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            return self::withTrashed()->where(['task_id' => ['in', $ids]])->column('*', 'task_id');
        }
        catch (\Exception $e)
        {
            Log::write('ZyhsUserQuestionComment model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['is_hide', 'uid', 'task_id', 'level', 'astr_id']);
        }

        return $data;
    }

    /**
     * @param int $taskId
     * @return array|null
     * @throws \Exception
     */
    public function getCommentData(int $taskId)
    {
        $commentData = $this->getInfoById([$taskId]);
        if ($commentData)
        {
            $tids = explode(',', $commentData['tids']);

            $tidInfos = (new ZyhsTag())->batchGetInfoByIds($tids);

            $tagNames = array_column($tidInfos, 'tag_name');

            return [
                'level' => $commentData['level'],
                'tag_names' => $tagNames,
                'comment' => $commentData['comment'],
            ];
        }
        return null;
    }
}
